//
//  FFloatButton.m
//  Foundation
//
//  Created by 吴新庭 on 2019/9/4.
//

#import "FFloatButton.h"

@interface FFloatButton ()

@property (nonatomic, weak) UIView *dockedView;
@property (nonatomic, assign) NSTimeInterval interval;

@property (nonatomic, strong) UIPanGestureRecognizer *panGR;

@end

@implementation FFloatButton

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.showsTouchWhenHighlighted = YES;
        self.dockOffset = -1;
        
        [self addTarget:self action:@selector(undock) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)setMoveable:(BOOL)moveable {
    _moveable = moveable;
    
    if (moveable && !self.panGR) {
        self.panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoveGR:)];
        [self addGestureRecognizer:self.panGR];
    }
}

- (void)autoDockForView:(UIView *)view withInterval:(NSTimeInterval)interval {
    self.dockedView = view;
    self.interval = interval;
    if (self.interval <= 0) {
        self.dockedView = nil;
        return;
    }
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(autoDock:) object:nil];
    [self performSelector:@selector(autoDock:) withObject:nil afterDelay:interval];
}

- (void)dockForView:(UIView *)view {
    CGRect frame = [view convertRect:self.frame fromView:self.superview];
//    self.layer.transform = CATransform3DRotate(CATransform3DIdentity, M_PI_4, 0, 1, 0);
    [UIView animateWithDuration:0.35 animations:^{
        CGFloat offset = self.dockOffset == -1 ? self.jk_width / 2.f : self.dockOffset;
        self.transform = CGAffineTransformTranslate(self.transform, offset, 0);
        self.alpha = 0.3f;
    }];
}

- (void)undock {
    CGAffineTransform transform = self.transform;
    transform.tx = 0;
    [UIView animateWithDuration:0.35 animations:^{
        self.transform = transform;
        self.alpha = 1.f;
    } completion:^(BOOL finished) {
        if (finished) {
            if (self.interval > 0) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(autoDock:) object:nil];
                [self performSelector:@selector(autoDock:) withObject:nil afterDelay:self.interval];
            }
        }
    }];
}

#pragma mark - Action
- (void)panMoveGR:(UIPanGestureRecognizer *)gr {
    CGPoint point = [gr translationInView:self];
    CGAffineTransform transform = CGAffineTransformTranslate(self.transform, 0, point.y);
    self.transform = transform;
    [gr setTranslation:CGPointZero inView:self];
}

- (void)autoDock:(id)sender {
    if (self.transform.tx == 0) {
        [self dockForView:self.dockedView];
    }
}

@end
